package com.da.lon.wang.xlg.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.activity.LoginActivity;
import com.da.lon.wang.xlg.activity.ProductsActivity;
import com.da.lon.wang.xlg.activity.ResultSearchActivity;
import com.da.lon.wang.xlg.adapter.CartAdapter;
import com.da.lon.wang.xlg.adapter.NoneCartAdapter;
import com.da.lon.wang.xlg.bean.CartBean;
import com.da.lon.wang.xlg.bean.CartBean.MResult.CartResult;
import com.da.lon.wang.xlg.bean.CartListBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.swipelistview.SwipeListView;
import com.da.lon.wang.xlg.util.BuyUtil;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.ToastUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.ScrollGridView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


public class CartFragment extends BaseFragment implements CartLienser,
        OnClickListener {

    private static final int DELAY = 0;
    public static int deviceWidth;
    // 存储列表文本内容的集合
    List<CartResult> datas;
    ImageView cart_frush_img;
    LinearLayout cart_content;
    private Context context;
    private float sum = 0.0f;
    private TextView sumTv;
    private SwipeListView cartListView;
    private CartAdapter adapter;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case DELAY:
                    adapter.selectAll(true);
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private CheckBox all;
    private boolean isCan = true;
    ;
    private HttpLoader<CartBean> loader;
    private TextView noneTv;
    private ScrollGridView noneGv;
    private List<String> nImgList;
    private List<String> nNameList = new ArrayList<String>();
    private List<String> nPricespeList;
    private List<String> nPriceList;
    private List<String> nZkList;
    private List<String> nUrList;
    private LinearLayout bottom;
    private LinearLayout somethingLayout;
    private ScrollView nothingLayout;
    private LinearLayout topbagLayout;
    private Button finalbutton;
    private String needCoordinates;
    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup var2) {
        view = inflater.inflate(R.layout.ocoffee_cart_fragment, null);
        return view;
    }

    @Override
    protected void initView() {
        context = getActivity();
        bottom = (LinearLayout) view.findViewById(R.id.bottom_frg);
        somethingLayout = (LinearLayout) view
                .findViewById(R.id.ocoffee_cart_something);
        nothingLayout = (ScrollView) view
                .findViewById(R.id.ocoffee_cart_nothing);
        topbagLayout = (LinearLayout) view
                .findViewById(R.id.ocoffee_cart_topbag);
        topbagLayout.setVisibility(View.GONE);
        cart_frush_img = (ImageView) view.findViewById(R.id.frush_img);
        cart_content = (LinearLayout) view.findViewById(R.id.cart_content);
        cart_frush_img.setOnClickListener(this);
        initView(view);
        initView1(view);
    }

    public void onResume() {
        super.onResume();
        sum = 0;
        if (nNameList != null) {
            nNameList.clear();
        }
        getData();
        sumTv.setText("合计: ￥0.00" + "\n不含运费");
        selectAll(false);
        MobclickAgent.onPageStart("CartFragment");
        MobclickAgent.onResume(getActivity());
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("CartFragment");
        MobclickAgent.onPause(getActivity());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        try {
            if (!hidden) {
                sum = 0;
                if (nNameList != null) {
                    nNameList.clear();
                }
                getData();
                sumTv.setText("合计: ￥0.00" + "\n不含运费");
                selectAll(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView1(View view) {
        noneTv = (TextView) view.findViewById(R.id.ocoffee_cart_none_tv);
        noneGv = (ScrollGridView) view.findViewById(R.id.ocoffee_cart_none_gv);

        noneTv.setOnClickListener(this);

        nImgList = new ArrayList<String>();

        nPricespeList = new ArrayList<String>();
        nPriceList = new ArrayList<String>();
        nZkList = new ArrayList<String>();
        nUrList = new ArrayList<String>();

    }

    private void initData() {

        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.add("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                + "disp"));
        params.add("version", "21");
        params.put("deviceId", MyApplication.getDeviceId());
        params.put("shop_id", MyApplication.getShopId());
        client.post(XLGConstants.URL + "Cart-disp", params,
                new JsonHttpResponseHandler("utf-8") {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);

                        try {
                            if ("000000".equals(response.getString("code"))) {
                                JSONObject result = response
                                        .getJSONObject("result");
                                CartListBean result2 = new CartListBean();
                                JSONArray array = result
                                        .getJSONArray("like_list");
                                JSONObject object = result
                                        .getJSONObject("area");

                                result2.setLike_list(array);
                                result2.setArea(object);
                                if (nNameList != null) {
                                    nNameList.clear();
                                }
                                for (int i = 0; i < +result2.getLike_list()
                                        .length(); i++) {
                                    JSONObject obj = result2.getLike_list()
                                            .getJSONObject(i);
                                    nImgList.add(obj.getString("bigimage"));
                                    nNameList.add(obj.getString("name"));
                                    nPriceList.add(obj.getString("price"));
                                    nPricespeList.add(obj.getString("pricespe"));
                                    nZkList.add(obj.getString("zk"));
                                    nUrList.add(obj.getString("product_number"));
                                }
                                noneGv.setAdapter(new NoneCartAdapter(context,
                                        nImgList, nNameList, nPriceList,
                                        nPricespeList, nZkList));
                                noneGv.setOnItemClickListener(new OnItemClickListener() {

                                    @Override
                                    public void onItemClick(
                                            AdapterView<?> parent, View view,
                                            int position, long id) {
                                        Intent intent = new Intent(context,
                                                ProductsActivity.class);

                                        String product_number = nUrList
                                                .get(position);
                                        PreferenceUtils
                                                .getInstance()
                                                .SetSettingString(
                                                        PreferencesConfig.PRODUCT_NUMBER,
                                                        product_number);
                                        startActivity(intent);

                                    }
                                });
                            }
                        } catch (JSONException e) {
                        }
                    }
                });

    }

    private void initView(View view) {

        all = (CheckBox) view.findViewById(R.id.all);
        sumTv = (TextView) view.findViewById(R.id.sum);
        finalbutton = (Button) view.findViewById(R.id.finalbutton);

        finalbutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (TextUtils.isEmpty(PreferenceUtils.getInstance()
                        .getSettingStr(PreferencesConfig.USER_KEY, ""))) {
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.putExtra("isGotoHome", false);
                    context.startActivity(intent);
                } else if (adapter != null) {
                    String result = adapter.getIds();
                    if (result.equals("")) {
                        Toast.makeText(CartFragment.this.getActivity(),
                                "你还没有选择商品", 0).show();
                    } else {

                        new BuyUtil(getActivity()).getTakeGoodsType(result,
                                needCoordinates);
                    }
                }
            }
        });

        cartListView = (SwipeListView) view.findViewById(R.id.cart_listview);
        deviceWidth = getDeviceWidth();

        reload();

        all.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                if (isCan && adapter != null) {
                    adapter.selectAll(arg1);
                }

            }
        });

    }

    private void reload() {
        // TODO Auto-generated method stub
        cartListView.setSwipeMode(SwipeListView.SWIPE_MODE_LEFT);
        cartListView.setSwipeActionLeft(SwipeListView.SWIPE_ACTION_REVEAL);
        cartListView.setOffsetLeft(deviceWidth * 3 / 4);
        cartListView.setAnimationTime(0);
        cartListView.setSwipeOpenOnLongPress(false);
    }

    private int getDeviceWidth() {
        return getResources().getDisplayMetrics().widthPixels;
    }

    private void getData() {
        if (!MyApplication.isNetworkAvailable(getActivity())) {
            showDialog();
            cart_content.setVisibility(View.GONE);
            cart_frush_img.setVisibility(View.VISIBLE);
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                        dismissDialog();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } else {
            loader = new HttpLoader<CartBean>(getActivity(), XLGConstants.URL
                    + "/Cart-disp", CartBean.class, 60 * 1000);
            AjaxParams params = new AjaxParams();

            params.put("id", MyApplication.getUserId());
            params.put("deviceId", MyApplication.getDeviceId());

            params.put("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                    + "disp"));
            loader.setManagerListener(new OnWebLoadListener<CartBean>() {

                @Override
                public void OnStart() {
                    showDialog();
                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                }

                @Override
                public void onSuccess(CartBean t) {
                    dismissDialog();
                    try {
                        CartBean bean = (CartBean) t;
                        if (t != null && bean.getCode().equals("000000")
                                && bean.getResult() != null) {
                            cart_content.setVisibility(View.VISIBLE);
                            cart_frush_img.setVisibility(View.GONE);
                            datas = bean.getResult().cart_result;
                            needCoordinates = bean.getResult()
                                    .getNeedCoordinates();
                            if (datas != null && !datas.isEmpty()) {
                                bottom.setVisibility(View.VISIBLE);
                                somethingLayout.setVisibility(View.VISIBLE);
                                nothingLayout.setVisibility(View.GONE);
                                if (getActivity() != null) {
                                    adapter = new CartAdapter(getActivity(),
                                            datas, CartFragment.this);
                                    if (adapter != null) {
                                        cartListView.setAdapter(adapter);
                                        handler.sendEmptyMessageDelayed(DELAY,
                                                100);
                                    }
                                }
                                if (datas.size() > 1) {
                                    topbagLayout.setVisibility(View.VISIBLE);
                                } else {
                                    topbagLayout.setVisibility(View.GONE);
                                }

                            } else {
                                bottom.setVisibility(View.GONE);
                                somethingLayout.setVisibility(View.GONE);
                                nothingLayout.setVisibility(View.VISIBLE);
                                topbagLayout.setVisibility(View.GONE);
                                initData();
                            }
                        } else {
                            cart_content.setVisibility(View.GONE);
                            cart_frush_img.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            loader.loadData(params);
        }
    }

    @Override
    public void selectAll(boolean flag) {
        try {
            isCan = false;
            all.setChecked(flag);
            isCan = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void soleChage(float num) {
        try {
            sum = sum + num;
            if (sum >= 0) {
                DecimalFormat fnum = new DecimalFormat("##0.00");
                String dd = fnum.format(sum);
                sumTv.setText("合计: ￥" + dd + "\n不含运费");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void can() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ocoffee_cart_none_tv:
                Intent intent = new Intent(context, ResultSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.frush_img:
                getData();
                break;
            default:
                break;
        }
    }

    @Override
    public void delete(String id) {
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.add("id", MyApplication.getUserId());
        params.add("ids", id);
        params.put("deviceId", MyApplication.getDeviceId());
        params.put("shop_id", MyApplication.getShopId());
        params.add("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                + "delete"));
        client.post(XLGConstants.URL + "Cart-delete", params,
                new JsonHttpResponseHandler("utf-8") {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {

                        try {
                            String code = response.getString("code");
                            if ("000000".equals(code)) {
                                Toast.makeText(CartFragment.this.getActivity(),
                                        "删除成功", 0).show();
                                // sumTv.setText("合计: ￥0.00" + "\n不含运费");
                                // all.setChecked(false);
                                sum = 0.0f;
                                getData();
                            } else {
                                ToastUtils.showShort(getActivity(),
                                        response.getString("message"));
                            }
                        } catch (JSONException e) {

                        }
                        super.onSuccess(statusCode, headers, response);
                    }
                });
    }

    @Override
    protected void RefreshData() {
        // TODO Auto-generated method stub
        getData();
    }

}
